<template>
  <common-header page-title="助农产品" />
  <div class="container">
    <section class="section-block">
      <div class="header-container">
        <h2 class="section-title">
          <i class="el-icon-goods"></i> 特色农产品推荐
          <span class="section-subtitle">精选优质农产品，助力乡村振兴</span>
        </h2>
      </div>
      <el-card class="product-card" shadow="hover" :body-style="{ padding: '16px' }">
        <el-row :gutter="20" class="product-row">
          <el-col
              v-for="(item, index) in products"
              :key="index"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="product-col"
          >
            <el-card
                class="product-item"
                :class="{ 'disabled-item': item.stock === 0 }"
                shadow="hover"
                :body-style="{ padding: '16px', display: 'flex', flexDirection: 'column' }"
                @click="item.stock !== 0 ? handleProductClick(item) : null"
            >
              <div class="product-image">
                <div class="image-placeholder" v-if="!item.imageUrls && !item.image"></div>
                <img :src="item.imageUrls || item.image" alt="商品图片" class="product-img" />
                <div v-if="item.stock === 0" class="sold-out-badge">
                  <span>已售罄</span>
                </div>
              </div>

              <h3 class="product-name">{{ item.name }}</h3>

              <div class="price-wrapper">
                <span class="current-price">¥{{ item.price }}</span>
                <span class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</span>
              </div>

              <div class="product-info">
                <el-tag type="warning" size="small" effect="dark">销量 {{ item.sales }}</el-tag>
                <el-tag type="info" size="small" effect="dark">库存 {{ item.stock }}件</el-tag>
              </div>

              <div class="button-wrapper">
                <el-button v-if="item.stock <= 0" type="info" size="small" disabled>已售罄</el-button>
                <div v-else class="action-buttons">
                  <el-button type="primary" size="small" @click.stop="buyNow(item)">立即购买</el-button>
                  <el-button type="success" size="small" @click.stop="addToCart(item)">
                    <i class="el-icon-shopping-cart-2"></i> 加入购物车
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </section>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import request from '@/utils/request'
import CommonHeader from '@/views/user/support/components/CommonHeader.vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'

const router = useRouter()
const products = ref([])
const loading = ref(false)

const isProductAvailable = (product) => {
  if (!product || !product.id || product.stock <= 0) {
    ElMessage.warning('该商品已售罄')
    return false
  }
  return true
}

const buyNow = (product) => {
  if (!isProductAvailable(product)) return
  router.push({name: 'OrderConfirm', params: {id: product.id}})
}

const addToCart = async (product) => {
  if (!isProductAvailable(product)) return

  const cartAddDto = {
    productId: product.id,
    quantity: 1
  }

  try {
    const res = await request.post('/api/v1/cart/add', cartAddDto)
    if (res.code === 2000) {
      ElMessage.success('已加入购物车')
    } else {
      ElMessage.error(res.msg || '加入购物车失败')
    }
  } catch (err) {
    console.error('加入购物车异常:', err)
    ElMessage.error('网络异常，请检查后端服务是否启动')
  }
}

const handleProductClick = (item) => {
  if (!item || !item.id) {
    alert("该商品暂无详情");
    return;
  }
  router.push({
    path: '/product/detail',
    query: {id: item.id}
  });
}

const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await request.get("/api/v1/government/public/list")
    if (res.code === 2000 && Array.isArray(res.data)) {
      products.value = res.data.map(p => ({
        ...p,
        image: p.imageUrls || p.image,
        originalPrice: p.price * 1.2 // 模拟原价
      }))
    } else {
      ElMessage.error('获取商品失败')
    }
  } catch (err) {
    console.error('获取商品数据失败:', err)
    ElMessage.error('网络异常，请检查后端服务是否启动')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 60px);
}

.section-block {
  margin-bottom: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.header-container {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-title {
  color: var(--text-color);
  font-size: 2rem;
  margin: 0;
  font-weight: 600;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.section-subtitle {
  font-size: 1rem;
  color: #909399;
  margin-top: 8px;
  font-weight: 400;
}

.product-card {
  margin-top: 20px;
  border-radius: 12px;
}

.product-row {
  margin-bottom: -20px;
}

.product-col {
  margin-bottom: 20px;
  padding-left: 10px;
  padding-right: 10px;
}

.product-item {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  border-radius: 8px;
  cursor: pointer;
  border: none;
  overflow: hidden;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.disabled-item {
  opacity: 0.7;
  cursor: not-allowed;
  position: relative;
}

.disabled-item .product-image {
  position: relative;
}

.sold-out-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 2;
}

.product-image {
  width: 100%;
  height: 180px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  border-radius: 4px;
  margin-bottom: 15px;
  position: relative;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.product-img {
  max-width: 100%;
  max-height: 180px;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.product-item:hover .product-img {
  transform: scale(1.05);
}

.product-name {
  color: #303133;
  font-size: 1.1rem;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  text-align: center;
}

.price-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 15px 0;
  flex-wrap: wrap;
}

.current-price {
  color: #f56c6c;
  font-size: 1.4rem;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #909399;
  font-size: 0.9rem;
  text-decoration: line-through;
  position: relative;
  top: 2px;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  flex-wrap: wrap;
  gap: 8px;
}

.product-info .el-tag {
  margin: 2px 0;
}

.button-wrapper {
  margin-top: auto;
  padding-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #f0f0f0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  flex: 1;
  min-width: 100px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .section-title {
    font-size: 1.5rem;
  }

  .section-subtitle {
    font-size: 0.9rem;
  }

  .product-col {
    padding-left: 5px;
    padding-right: 5px;
  }

  .product-item {
    padding: 12px !important;
  }

  .product-name {
    font-size: 1rem;
  }

  .current-price {
    font-size: 1.2rem;
  }
}
</style>